
#include "SList.h"


void SListInit(SLTNode* phead) {
	SLTNode* plist = (SLTNode*)malloc(sizeof(SLTNode));
	phead->data = 0;
	phead->next = NULL;
}

void SListPrint(SLTNode* phead) {
	SLTNode* cur = phead;
	while (cur != NULL) {
		printf("cur->data = %d\n", cur->data);
		cur = cur->next;
	}
}

SLTNode* BuyNode(SLTDataType x) {
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode != NULL) {
		newnode->data = x;
		newnode->next = NULL;
		return newnode;
	}
	return NULL;
}

void SListPushBack(SLTNode** pphead, SLTDataType x) {
	SLTNode* newnode = BuyNode(x);
	if(newnode != NULL){
		if (*pphead == NULL) {
			*pphead = newnode;
		}
		else {
			SLTNode* tail = *pphead;
			while (tail->next != NULL)
				tail = tail->next;
			tail->next = newnode;
		}
	}
}

void SListPushFront(SLTNode** pphead, SLTDataType x) {
	SLTNode* newnode = BuyNode(x);

	newnode->next = *pphead;
	*pphead = newnode;
}

void SListPopFront(SLTNode** pphead) {
	if (*pphead != NULL) {
		SLTNode* front = *pphead;
		(*pphead) = (*pphead)->next;
		free(front);
		front = NULL;
	}
}

void SListPopBack(SLTNode** pphead) {
	if (*pphead != NULL) {
		SLTNode* cur = *pphead;
		SLTNode* tail = (*pphead)->next;
		while (tail->next != NULL && cur->next != NULL) {
			tail = tail->next;
			cur = cur->next;
		}
		cur->next = NULL;
		free(tail);
		tail = NULL;
	}
}

SLTNode* SListFind(SLTNode* phead, SLTDataType data) {
	SLTNode* cur = phead;
	while (cur != NULL) {
		if (cur->data == data)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void SListInsert(SLTNode** pphead, SLTNode* pos, SLTDataType data) {
	if (pos == *pphead) {
		SListPushFront(pphead, data);
	}
	else {
		SLTNode* newnode = BuyNode(data);
		SLTNode* cur = *pphead;
		while (cur->next != pos)
			cur = cur->next;
		cur->next = newnode;
		newnode->next = pos;
	}
}

void SListErase(SLTNode** pphead, SLTNode* pos) {
	if (pos == *pphead) {
		SLTNode* tmp = *pphead;
		*pphead = (*pphead)->next;
		free(tmp);
		tmp = NULL;
	}
	else
	{
		SLTNode* prev = *pphead;
		while (prev->next != pos)
			prev = prev->next;

		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
